package com.jeeplus.test.jlnu.archivalInfo.controller;

import com.alibaba.excel.EasyExcel;
import com.jeeplus.test.jlnu.admissionInfo.utils.MyWebSocketHandler;
import com.jeeplus.test.jlnu.archivalInfo.domain.vo.ArchivalInfoExcelVO;
import com.jeeplus.test.jlnu.archivalInfo.service.ExcelArcService;
import com.jeeplus.test.jlnu.archivalInfo.utils.ArchivalInfoDataListener;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Api(tags = "档案信息导入")
@RestController
@Slf4j
@RequestMapping("/excel")
public class ExcelArchivalController {


    @Autowired
    private MyWebSocketHandler webSocketHandler;

    @Autowired
    private ExcelArcService excelArcService;


    /**
     * 档案信息导入
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/importArchives")
    public ResponseEntity<String> importArchives(@RequestParam("file") MultipartFile file, @RequestParam("officeId") String officeId) throws IOException {
        // 清除之前的进度
        webSocketHandler.sendProgressUpdate(0);
        int totalRecords = getTotalRecords(file);
        try {
            EasyExcel.read(file.getInputStream(), ArchivalInfoExcelVO.class, new ArchivalInfoDataListener(excelArcService, progress -> {
                try {
                    webSocketHandler.sendProgressUpdate(progress);
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }, totalRecords,officeId)).sheet().headRowNumber(1).doRead();
            webSocketHandler.sendProgressUpdate(100);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok("导入已开始");
    }


    private int getTotalRecords(MultipartFile file) {
        int totalRecords = 0;
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(inputStream)) {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            totalRecords = sheet.getPhysicalNumberOfRows(); // 包括表头行数
            // 计算行数
//             totalRecords = sheet.getLastRowNum(); // 不包括表头
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常逻辑
        }
        return totalRecords;
    }
}
